package com.angel.controller;

import com.angel.bean.*;
import com.angel.bean.dto.GoodListDto;
import com.angel.bean.dto.PurchaseApplicationDetils;
import com.angel.dto.StockManageDto;
import com.angel.service.*;
import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.utils.AdminUserUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/stockManageController")
public class StockManageController {

    @Resource
    ProductService productService;
    @Resource
    PurchaseApplicationService purchaseApplicationService;
    @Resource
    EmployeeService employeeService;
    @Resource
    BranchesService branchesService;
    @Resource
    GoodsListService goodsListService;
    @Autowired
    private OtherlogService otherlogService;


    /**
     * 打开进货申请页面
     *
     * @return
     */
    @RequestMapping("/addApplication")
    public String addApplication(Model model) {
        // 申请人
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        if (principal.getEmployee().getBranchesId()==1){
           return "msg";
        }
        // 申请时间m
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        model.addAttribute("aplicDate", sdf.format(date));


        String aplicman = principal.getEmployee().getEmName();
        model.addAttribute("aplicman", aplicman);
        // 联系电话
        String aplictel = principal.getEmployee().getEmTel();
        model.addAttribute("aplictel", aplictel);
        return "stockManageAdd";
    }


    /**
     * 获得当前分店的商品
     *
     * @return
     */
    @RequestMapping("/findBranchProduct")
    @ResponseBody
    public Object findBranchProduct() {
        Product product = new Product();
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        int branchesId = principal.getEmployee().getBranchesId();
        Branches par = new Branches();
        par.setBranId(branchesId);
        par = branchesService.findOneBranches(par);
        // 设置分店id为当前登录员工的分店id查询出该分店的父店商品
        product.setBranId(par.getUpperId());
        product.setState(1);
        Map<Object, Object> map = new HashMap<>();
        List<Product> tproductList = productService.findProduct(product);
        if (tproductList != null) {
            map.put("productList", tproductList);
        }
        return map;
    }

    /**
     * 查询单个产品
     *
     * @return
     */
    @RequestMapping("/findOneProduct")
    @ResponseBody
    public Object findOneProduct(@RequestParam(value = "proid") int proid) {
        System.out.println("--------------------------" + proid);
        Product product = new Product();
        product.setProductId(proid);
        Product pro = productService.findOne(product);
        Map<Object, Object> map = new HashMap<>();
        if (pro != null) {
            map.put("pro", pro);
        }
        return map;
    }

    /**
     * 添加进货申请
     *
     * @return
     */
    @RequestMapping("/addPurchaseApplication")
    @ResponseBody
    public Object addPurchaseApplication(StockManageDto stockManageDto) {
        System.out.println("---------------------- 清单表 ----------------------");
        PurchaseApplication purchaseApplication = new PurchaseApplication();

        // 获得申请人信息
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        int empId = principal.getId();
        Employee employee = new Employee();
        employee.setEmId(empId);
        Employee emp = employeeService.findOne(employee);

        // 获得分店信息
        Branches branches = new Branches();
        branches.setBranId(emp.getBranchesId());
        Branches bra = branchesService.findOneBranches(branches);

        Timestamp currentDate = new Timestamp(System.currentTimeMillis());

        // 子店id
        purchaseApplication.setSubId(emp.getBranchesId());
        // 父店id
        purchaseApplication.setUpperId(bra.getUpperId());
        // 申请时间
        purchaseApplication.setAplicDate(currentDate);
        // 进货总价
        purchaseApplication.setPurchPrice(stockManageDto.getPurchPrice());
        // 申请状态
        purchaseApplication.setAplicState(0);
        // 申请人
        purchaseApplication.setAplicman(emp.getEmName());
        // 联系电话
        purchaseApplication.setAplictel(emp.getEmTel());
        // 激活状态
        purchaseApplication.setState(1);
        // 备注
        purchaseApplication.setAplicNote(stockManageDto.getAplicNote());

        int result = purchaseApplicationService.insert(purchaseApplication);

        System.out.println("---------------------- 进货表 ----------------------");

        List<String> list = new ArrayList<>();
        for (int i = 0; i < stockManageDto.getProductId().size(); i++) {

            GoodsList goodsList = new GoodsList();
            // 进货申请表id
            goodsList.setAplicId(purchaseApplication.getId());
            // 商品id
            goodsList.setProductId(stockManageDto.getProductId().get(i));
            // 商品数量aaa
            goodsList.setAmount(stockManageDto.getAmount().get(i));
            // 总价aaa
            Product product = new Product();
            product.setProductId(stockManageDto.getProductId().get(i));
            product = productService.findOne(product);
            double sumPrice = product.getPurchasePrice()* stockManageDto.getAmount().get(i);
            goodsList.setSumPrice(sumPrice);
            // 激活状态
            goodsList.setState(0);

            int result2 = goodsListService.insert(goodsList);
            if (result2 == 0) {
                list.add("fail");
            }
        }
        Map<Object, Object> map = new HashMap<>();
        if (result != 0) {
            if (list.size() == 0) {
                map.put("result", "success");
            }
        }
        return map;
    }

    /**
     * 跳转到订单管理页面
     * @param model
     * @return
     */
    @RequestMapping("/getstock")
    public String getStock(@RequestParam(value = "pn", defaultValue = "1") String pn,Model model){
        //将前端传回的参数改为String类型，然后进行数据类型转换，如果出现问题，则进行异常处理，异常可以是空处理
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }

        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        Employee employee = principal.getEmployee();
        // 查看申请表，子店是否有申请进货
        PurchaseApplication purchaseApplication = new PurchaseApplication();
        purchaseApplication.setUpperId(employee.getBranchesId());
        //在查询之前传入当前页，然后多少记录
        PageHelper.startPage(pageNo, 10);
        List<PurchaseApplicationDetils> purchaseApplicationList = purchaseApplicationService.finddetilPurchaseApplication(purchaseApplication);
        PageInfo pageInfo = new PageInfo(purchaseApplicationList);
      //  model.addAttribute("list",purchaseApplicationList);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        return "stockManager";
    }

    /**
     *h获取我的进货列表
     * @param pn
     * @param model
     * @return
     */
    @RequestMapping("/mygetstock")
    public String getMyStock(@RequestParam(value = "pn", defaultValue = "1") String pn,Model model){
        //将前端传回的参数改为String类型，然后进行数据类型转换，如果出现问题，则进行异常处理，异常可以是空处理
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }

        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();

        Employee employee = principal.getEmployee();
        // 查看申请表，子店是否有申请进货
        PurchaseApplication purchaseApplication = new PurchaseApplication();
        if (employee.getEmTypeId() !=1){
            purchaseApplication.setSubId(employee.getBranchesId());
        }

        //在查询之前传入当前页，然后多少记录
        PageHelper.startPage(pageNo, 10);
        List<PurchaseApplicationDetils> purchaseApplicationList = purchaseApplicationService.finddetilPurchaseApplication(purchaseApplication);
        PageInfo pageInfo = new PageInfo(purchaseApplicationList);
        if (pageInfo != null) {
            model.addAttribute("pageInfo", pageInfo);
        }
        return "MystockManager";
    }

    /**
     *
     * @return
     */
    @RequestMapping("/getlist")
    @ResponseBody
    public Object getGoodList(@RequestParam(value = "purid") String purid) {
        Integer puid =null;
        try {
            puid = Integer.valueOf(purid);
        }catch (Exception e) {
            return null;
        }

        GoodsList goodsList = new GoodsList();
        goodsList.setAplicId(puid);
       List<GoodListDto> gpt= goodsListService.findProductGoodsList(goodsList);
        if (gpt!=null && !gpt.isEmpty()){
            return gpt;
        }
        return null;
    }


    /*********************************************************进货流程处理****************************************************/

    /**检查货源是否充足，如果不充足，则状态改为等待发货，若货源充足，则状态位发货状态、、
     * 进货流程处理
     *
     * @return
     */
    @RequestMapping("/haveApplication")
    @ResponseBody
    public Object HaveApplication(@RequestParam("id") String id) {
        Map<Object, Object> map = new HashMap<>();
            Integer acid =null;
            try {
                acid = Integer.valueOf(id);
            }catch (Exception e){
                map.put("result","参数异常！");
                return map;
            }
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        // 当前分店id
        int branchesId = principal.getEmployee().getBranchesId();
        // 查看申请表，子店是否有申请进货
        GoodsList goodsList = new GoodsList();
        goodsList.setAplicId(acid);
        List<GoodListDto> goodListDtos = goodsListService.findProductGoodsList(goodsList);
        //数量标识符
        boolean amountflag = false;
        for (int i =0 ;i<goodListDtos.size();i++){
            GoodListDto goodListDto = goodListDtos.get(i);
            if (goodListDto.getAmount() > goodListDto.getProStock()){
                amountflag = true;
            }
        }
        PurchaseApplication tmpPurchaseApplication = new PurchaseApplication();
        tmpPurchaseApplication.setAplicState(1);
        tmpPurchaseApplication.setId(acid);
        if (amountflag){
            purchaseApplicationService.update(tmpPurchaseApplication);
            map.put("result","您需要补充货源！");
            return map;
        }

        PurchaseApplication purchaseApplication = new PurchaseApplication();
        //父店申请id
        purchaseApplication.setId(acid);
        //
        purchaseApplication = purchaseApplicationService.findOne(purchaseApplication);

        if (purchaseApplication ==null){
            map.put("result", "没有进货申请");
            return map;
        }
        //进行进货订单处理
        if (purchaseApplication.getAplicState() != 2 && purchaseApplication.getAplicState() != 3){
            try {
                Map tmp  =  purchaseApplicationService.detilGoods(goodListDtos,purchaseApplication);
                map.put("result","处理成功成功");
                map.put("data",tmp);
            } catch (Exception e) {
                map.put("result","处理失败");
            }
        }else {
            map.put("result","该订单不需要处理");
        }
        return map;
    }

    /**
     * 确认收货处理
     * @param id id
     * @return
     */
    @RequestMapping("/updateApplication")
    @ResponseBody
    public Object updateStatus(@RequestParam("id") String id,@RequestParam(value = "status",defaultValue = "3")String status){
        Map<Object, Object> map = new HashMap<>();
        map.put("success",false);
        Integer acid =null;
        Integer state =3;
        try {
            acid = Integer.valueOf(id);
            state =Integer.valueOf(status);
        }catch (Exception e){
            map.put("result","参数异常！");
            return map;
        }
        PurchaseApplication purchaseApplication = new PurchaseApplication();
        purchaseApplication.setAplicState(state);
        purchaseApplication.setId(acid);
        int result = purchaseApplicationService.update(purchaseApplication);
        if (result!=0){
            map.put("success",true);
            map.put("result","状态更新成功！");
        }
        return map;
    }
}
